package com.umessage.common.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

@Service
public class SimpleSmsUtil {
	@Value("${umessage.smsServerUrl}")
	private String smsServerUrl;

	/**
	 * 发送短消息
	 * 
	 * @param mobile
	 * @param msg
	 */
	public void sendMsg(String mobile, String hotelName, String msg) {
		Map<String, String> param = new HashMap<String, String>();
		try {
			param.put("smsChannel", "");
			param.put("sendTime", "");
			param.put("sendMan", "");
			// 短信内容
			String sign = getVerificationChannelSign(mobile);
			param.put("smsType", "4");
			param.put("mobile", mobile);
			param.put("smsContent", URLEncoder.encode(String.format("【%s】%s", hotelName, msg), "utf-8"));
			param.put("channelName", "tmc");
			param.put("status", "1");// 0就是没有上行,1是有上行(returnContent不能为空)
			param.put("returnContent", URLEncoder.encode("td,gh", "utf-8"));
			param.put("sign", sign);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e.getMessage(), e);
		}

		String res = "0";
		try {
			String url = "http://39.104.68.154:8081/";
			if(smsServerUrl != null) {
				url = smsServerUrl;
			}
			res = HttpRequestUtil.send(url, param, "UTF-8");
			JSONObject obj = JSON.parseObject(res);
			String resultCode = obj.getString("resultCode");
			if (!resultCode.equals("0")) {
				throw new RuntimeException("sms server return error code");
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}

	}

	/** 生成sign **/
	private String getVerificationChannelSign(String mobile) {
		String channelSign = MD5Util.MD5Encode("tmc" + "tmc_2017" + mobile, "");
		return channelSign;
	}

}
